package com.mxdx.edu.controller;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mxdx.edu.enums.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.mxdx.edu.common.ApiResult;
import com.mxdx.edu.common.CommonUtils;
import com.mxdx.edu.common.Digests;
import com.mxdx.edu.common.log.AppLogger;
import com.mxdx.edu.constant.StaticConstants;
import com.mxdx.edu.model.StudentInfo;
import com.mxdx.edu.service.ISchoolStatusService;
import com.mxdx.edu.service.IStudentService;
import com.mxdx.edu.util.ServletUtil;
import com.mxdx.edu.util.StringUtils;

/**
 * 用户Controller
 * 
 * @author howie
 *
 */
@Controller
@RequestMapping(value = "/edu")
public class StudentController extends BaseController {

	private AppLogger logger = new AppLogger(StudentController.class);

	@Resource
	private IStudentService studentService;

	@Resource
	private ISchoolStatusService schoolStatusService;

	@Value("${personal.url}")
    private String personalUrl;

	@Value("${sales.man.url}")
    private String salesManUrl;

	@Value("${training.category.url}")
    private String trainingCategoryUrl;

	@RequestMapping(value = "/public/toRegister")
	public ModelAndView toRegister(HttpServletRequest request) {
		logger.entry(ServletUtil.getClientIp(request), "toRegister");
		ModelAndView result = new ModelAndView("/h5/zhuce");
		String recommendationCode = ServletUtil.getParameterStr(request, "recommendationCode", "");
		if (!"".equals(recommendationCode)) {
			result.addObject("recommendationCode", recommendationCode);
		}
		logger.info(ServletUtil.getClientIp(request));
		return result;

	}

	@RequestMapping(value = "/static/jumpOther")
	public ModelAndView jumpOther(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String token = sessionUtil.getTokenSession(request);
        String jumpType = request.getParameter("jumpType");
        String collegeId = "";
        String toUrl;
        if(JumpTypeEnums.PERSONAL_TYPE.getCode().equals(jumpType)){
			toUrl = personalUrl;
		}else{
			toUrl = trainingCategoryUrl;
			collegeId = request.getParameter("collegeId");
		}
        String url = toUrl+"?token="+(StringUtils.isEmpty(token)?"":token)+"&collegeId="+collegeId;
        response.sendRedirect(url);
		return null;
	}

	/**
	 * 密码校验
	 * 
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/public/checkPassword")
	public ApiResult<Map<String, Object>> checkPassword(
			HttpServletRequest request) {
		logger.entry(ServletUtil.getClientIp(request), "checkPassword");
		ApiResult<Map<String, Object>> apiResult = new ApiResult<>();
		Map<String, Object> retMap = new HashMap<>();
		String password = ServletUtil.getParameterStr(request, "password", "");
		String passwordAgain = ServletUtil.getParameterStr(request,
				"passwordAgain", "");
		// 验证密码
		if (!password.equals(passwordAgain)) {
			apiResult.setStatus(ErrorEnums.PASSWORD_AGREE.getCode());
			apiResult.setMessage(ErrorEnums.PASSWORD_AGREE.getDesc());
		}
		apiResult.setResult(retMap);
		logger.info(ServletUtil.getClientIp(request));
		return apiResult;
	}

	/**
	 * 校验图片验证码
	 * 
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/public/sendSms")
	public ApiResult<Map<String, Object>> sendSms(HttpServletRequest request) {
		ApiResult<Map<String, Object>> apiResult = new ApiResult<>();
		String mobilePhone = ServletUtil.getParameterStr(request,
				"mobilePhone", "");// 手机号
		String uuid = ServletUtil.getParameterStr(request, "uuid", "");// 图片验证码
		String imgCode = ServletUtil.getParameterStr(request, "imgCode", "");// 图片验证码

		Object codeObject = redisUtil.get(String.format("imageCode_%s", uuid));
		String orgImgCode = codeObject == null ? "" : codeObject.toString();

		if (StringUtils.isAnyEmpty(imgCode, mobilePhone)) {
			apiResult.setStatus("图片验证码和手机号不能为空");
			apiResult.setMessage(ErrorEnums.MUST_FIELD_IS_NULL.getCode());
			return apiResult;
		}

		if (!imgCode.equalsIgnoreCase(orgImgCode)) {
			removeImgCode(uuid); // 一个图片验证码只能用一次
			apiResult.setStatus(ErrorEnums.IMG_CODE_ERROR.getCode());
			apiResult.setMessage(ErrorEnums.IMG_CODE_ERROR.getDesc());
			return apiResult;
		}

		Map<String, Object> studentMap = studentService
				.findMapByPhoneNumber(mobilePhone);
		if (null == studentMap) {
			removeImgCode(uuid); // 一个图片验证码只能用一次
			apiResult.setStatus(ErrorEnums.PHONE_NUMBER_NO_EXIST.getCode());
			apiResult.setMessage(ErrorEnums.PHONE_NUMBER_NO_EXIST.getDesc());
			return apiResult;
		}

		//校验是否有效
		if (isAlreadySend(SmsTypeEnums.BACK_PASSWORD.getCode(), mobilePhone)) {
			apiResult.setStatus(ErrorEnums.SMS_ALREADY_SEND.getCode());
			apiResult.setMessage(ErrorEnums.SMS_ALREADY_SEND.getDesc());
			return apiResult;
		}
		//校验是否超过缓存时间
		if (isAlreadySendCache(SmsTypeEnums.BACK_PASSWORD.getCode(), mobilePhone)) {
			apiResult.setStatus(ErrorEnums.SMS_ALREADY_SEND.getCode());
			apiResult.setMessage(ErrorEnums.SMS_ALREADY_SEND.getDesc());
			return apiResult;
		}

		//String code = "666666"; // 测试写死6个6
		String code = StringUtils.generateCode(6);
		String result = smsUtil.sendSms(mobilePhone,code);
		if (!"OK".equals(result)) {
			apiResult.setStatus(ErrorEnums.SMS_ALREADY_FAILED.getCode());
			apiResult.setMessage(ErrorEnums.SMS_ALREADY_FAILED.getDesc());
			return apiResult;
		}

		redisUtil.set(String.format("%s_%s", //此处最好用setEx
				SmsTypeEnums.BACK_PASSWORD.getCode(), mobilePhone), code,
				smsLockExpireTime);
		redisUtil.set(String.format("%s_%s_cache", //此处最好用setEx
				SmsTypeEnums.BACK_PASSWORD.getCode(), mobilePhone), code,
				smsCacheLockExpireTime);

		return apiResult;
	}

	/**
	 * 用户注册
	 * 
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/public/register")
	public ApiResult<Map<String, Object>> register(HttpServletRequest request) {
		logger.entry(ServletUtil.getClientIp(request), "register");
		ApiResult<Map<String, Object>> apiResult = new ApiResult<>();
		String phoneNumber = ServletUtil.getParameterStr(request,
				"phoneNumber", "");// 手机号
		String userName = ServletUtil.getParameterStr(request, "userName", "");// 用户姓名
		String password = ServletUtil.getParameterStr(request, "password", "");// 用户密码

		String uuid = ServletUtil.getParameterStr(request, "uuid", "");// 图片验证码
		String imgCode = ServletUtil.getParameterStr(request, "imgCode", "");// 图片验证码
		String recommendationCode = ServletUtil.getParameterStr(request, "recommendationCode", "");// 推荐码

		logger.doInfo("register", String.format(
				"保存用户信息:phoneNumber:%s, userName:%s, password:%s", phoneNumber,
				userName, password));
		Map<String, Object> findMap = new HashMap<>();
		findMap.put("phoneNumber", phoneNumber);
		try {
			Object codeObject = redisUtil.get(String.format("imageCode_%s",
					uuid));
			String orgImgCode = codeObject == null ? "" : codeObject.toString();
			if (!imgCode.equalsIgnoreCase(orgImgCode)) {
				removeImgCode(uuid); // 一个图片验证码只能用一次
				apiResult.setStatus(ErrorEnums.IMG_CODE_ERROR.getCode());
				apiResult.setMessage(ErrorEnums.IMG_CODE_ERROR.getDesc());
				return apiResult;
			}

			// 校验手机号是否被注册，如果被注册则直接返回
			boolean checkPhone = studentService
					.checkStudentByPhoneNumber(findMap);
			if (!checkPhone) {
				apiResult.setStatus(ErrorEnums.PHONE_NUMBER_EXIST.getCode());
				apiResult.setMessage(ErrorEnums.PHONE_NUMBER_EXIST.getDesc());
				return apiResult;
			}
			StudentInfo studentInfo = new StudentInfo();
			String studentId = serialService.generateSerialNum(
					CreateTypeEnums.CREATE_STUDENT.getCode(), 7);
			studentInfo.setId(studentId);
			studentInfo.setPhoneNumber(phoneNumber);
			studentInfo.setStudentName(userName);
			studentInfo.setPassword(Digests.md5(password));
			studentInfo.setRecommendationCode(recommendationCode);
			studentInfo.setStudentType(StudentTypeEnums.REGISTER_STUDENTS
					.getCode());
			studentInfo.setMood("欢迎光临梦想在线！");
			studentInfo
					.setHeadPortrait("");
			studentService.save(studentInfo);
			// 写入session
			String token = sessionUtil.setTokenSession(request);
			Map<String, Object> map = new HashMap<>();
			map.put("phoneNumber", phoneNumber);
			map.put("studentName", userName);
			map.put("password", Digests.md5(password));
			map.put("studentType", String
					.valueOf(StudentTypeEnums.REGISTER_STUDENTS.getCode()));
			map.put("headPortrait", studentInfo.getHeadPortrait());
			map.put("mood", studentInfo.getMood());
			map.put("studentId", studentId);
			redisUtil.set(token, map);
			removeImgCode(uuid); // 一个图片验证码只能用一次
			logger.info(ServletUtil.getClientIp(request));
		} catch (Exception e) {
			super.dealException(ErrorEnums.SYSTEM_ERROR, e, apiResult, logger);
		}
		return apiResult;
	}

	/**
	 * 跳转登陆页面
	 * 
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/public/toLogin")
	public ModelAndView toLogin(HttpServletRequest request) {
		logger.entry(ServletUtil.getClientIp(request), "toLogin");
		ModelAndView result = new ModelAndView("/h5/denglu");
		String phoneNumber = "";
		String password = "";
//		String toUrl = ServletUtil.getParameterStr(request, "toUrl", "");
		// 获取用户cookies，如果有则直接填写账号密码
		Cookie[] cookies = request.getCookies();
		if (cookies != null && cookies.length > 0) {
			for (Cookie c : cookies) {
				if (StaticConstants.LOGIN_COOKIE.equals(c.getName())) {
					String token = c.getValue();
					Object object = redisUtil.get(token);
					if (object != null) {
						Map<String, Object> map = (Map<String, Object>) object;
						phoneNumber = CommonUtils.getStrValueFromMap(map,
								"phoneNumber", phoneNumber);
						password = CommonUtils.getStrValueFromMap(map,
								"password", phoneNumber);

					}
				}
				logger.doInfo("cookies", c);
			}
		}
		// 获取用户要访问页面，登录后直接跳转
		String toUrl = ServletUtil.getParameterStr(request, "toUrl", "");
		if (!"".equals(toUrl)) {
			result.addObject("toUrl", toUrl);
		}
		result.addObject("phoneNumber", phoneNumber);
		result.addObject("password", password);
		String recommendationCode = ServletUtil.getParameterStr(request, "recommendationCode", "");
		if(!"".equals(recommendationCode)){
			result.addObject("recommendationCode", recommendationCode);
		}
		logger.info(ServletUtil.getClientIp(request));
		return result;
	}



	/**
	 * 业务员登陆页面
	 *
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/public/salesManLogin")
	public ModelAndView salesManLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
		logger.entry(ServletUtil.getClientIp(request), "salesManLogin");
		String url = salesManUrl;
		response.sendRedirect(url);
		return null;
	}

	/**
	 * 登陆
	 * 
	 * @param request
	 * @returnf
	 */
	@ResponseBody
	@RequestMapping(value = "/public/login")
	public ApiResult<Map<String, Object>> login(HttpServletRequest request,
			HttpServletResponse response) {
		logger.entry(ServletUtil.getClientIp(request), "login");
		ApiResult<Map<String, Object>> result = new ApiResult<>();
		Map<String, Object> resultMap = new HashMap<>();
		String phoneNumber = ServletUtil.getParameterStr(request, "phoneNumber", "");
		String toUrl = ServletUtil.getParameterStr(request, "toUrl", "");
		String password = ServletUtil.getParameterStr(request, "password", "");
		String remFlag = ServletUtil.getParameterStr(request, "remFlag", "");
		String studentType = ServletUtil.getParameterStr(request, "studentType", "");
		logger.doInfo("login", String.format("phoneNumber:%s, password:%s, remFlag:%s, studentType:%s", phoneNumber,
				password, remFlag, studentType));
		Map<String, Object> findMap = new HashMap<>();
		try {
			// 通过手机号和md5加密后的密码查询用户信息，没有则返回登录失败
			// if("0".equals(loginType)){
			// password = Digests.md5(password);
			// }
			if(StringUtils.isAnyEmpty(phoneNumber,password)){
				result.setStatus(ErrorEnums.MUST_FIELD_IS_NULL.getCode());
				result.setMessage(ErrorEnums.MUST_FIELD_IS_NULL.getDesc());
				return result;
			}
			findMap.put("phoneNumber", phoneNumber);
			findMap.put("password", password);
			findMap.put("studentType", studentType);
			boolean checkLogin = studentService.checkLogin(findMap);
			if (!checkLogin) {
				result.setStatus(ErrorEnums.PHONE_AND_PASSWORD_FAIL.getCode());
				result.setMessage(ErrorEnums.PHONE_AND_PASSWORD_FAIL.getDesc());
				return result;
			}
			Map<String, Object> studentMap = studentService
					.findMapByPhoneNumberAndStudentType(phoneNumber,studentType);
			String token = sessionUtil.setTokenSession(request);
			redisUtil.set(token, studentMap);
			// 记住密码
			if (keepPasswordEnums.YES.getCode().equals(remFlag)) {
				// 创建Cookie对象
				Cookie nameCookie = new Cookie("loginCookie", token);
				// 设置Cookie的有效期为7天
				nameCookie.setMaxAge(60 * 60 * 24 * 7);
				response.addCookie(nameCookie);
			}
			/*studentType = CommonUtils.getStrValueFromMap(studentMap, "studentType", "0");
			if(!"".equals(toUrl) && StudentTypeEnums.SALES_MAN.getCode() != Integer.parseInt(studentType)) {
				resultMap.put("toUrl", toUrl+"?token="+token);
			}
			if(URL.equals(toUrl)){
				resultMap.put("toUrl", toUrl+"?token="+token);
			}else{
				// 如果学生是在校生则跳转到在校生页面
				if (StudentTypeEnums.ENROLLED_STUDENTS.getCode() == Integer
						.valueOf(studentType)) {
					resultMap.put("toUrl", "/auth/successIndex");
				}
				// 如果是业务员跳转到业务员页面
				if (StudentTypeEnums.SALES_MAN.getCode() == Integer
						.valueOf(studentType)) {
					resultMap.put("toUrl", "/auth/salesManInfo");
				}

				//预录生 游客在学历学位登录时 跳转到 首页  辅导课程 辅导动态 推荐报名 入学报到
				if(("/curriculum/auth/toCurriculum".equals(toUrl)
						|| "/continuingEducation/auth/examinationGroup".equals(toUrl)
						|| "/continuingEducation/auth/recommendEnroll".equals(toUrl)
						|| "/continuingEducation/auth/enrollmentReport".equals(toUrl) )
						&& (StudentTypeEnums.TOURISTS.getCode() == Integer.valueOf(studentType) || StudentTypeEnums.REGISTER_STUDENTS.getCode() == Integer.valueOf(studentType))){
					resultMap.put("toUrl", "/public/jxjyIndex");
				}

			}*/

            resultMap.put("toUrl", "/");
			logger.info(ServletUtil.getClientIp(request));
		} catch (Exception e) {
			super.dealException(ErrorEnums.SYSTEM_ERROR, e, result, logger);
		}
		result.setResult(resultMap);
		return result;
	}

	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value = "/auth/checkIdNumber")
	public ApiResult<Map<String, Object>> checkIdNumber(
			HttpServletRequest request, HttpServletResponse response) {
		logger.entry(ServletUtil.getClientIp(request), "login");
		ApiResult<Map<String, Object>> apiResult = new ApiResult<>();
		Map<String, Object> resultMap = new HashMap<>();

		String token = sessionUtil.getTokenSession(request);
		String studentId = super.getStudentId(request);
		Map<String, Object> map = (Map<String, Object>) redisUtil.get(token);
		String idNumber = ServletUtil.getParameterStr(request, "idNumber", "");
		String phoneNumber = CommonUtils.getStrValueFromMap(map, "phoneNumber",
				"");
		String studentName = CommonUtils.getStrValueFromMap(map, "studentName",
				"");
		Map<String, Object> param = new HashMap<>();
		param.put("idNumber", idNumber);
		logger.doInfo("查询学生学籍表:", param);
		try {
			if(StringUtils.isEmpty(idNumber)){
				apiResult.setStatus(ErrorEnums.CHECK_ID_NUMBER_FAIL.getCode());
				apiResult.setMessage(ErrorEnums.CHECK_ID_NUMBER_FAIL.getDesc());
				return apiResult;
			}
			// 身份证号查询学生学籍信息
			List<Map<String, Object>> maps = schoolStatusService
					.findListByMap(param);
			if (maps == null || maps.size() <= 0) {
				apiResult.setStatus(ErrorEnums.CHECK_ID_NUMBER_FAIL.getCode());
				apiResult.setMessage(ErrorEnums.CHECK_ID_NUMBER_FAIL.getDesc());
				return apiResult;
			}
			Map<String, Object> updateMap = new HashMap<>();
			updateMap.put("insStudentId", studentId);
			updateMap.put("idNumber", idNumber);
			updateMap.put("updateDate", new Date());
			updateMap.put("status", SchoolStatusEnums.NO.getCode());
			updateMap.put("mobilePhone", phoneNumber);
			updateMap.put("studentName", studentName);
			updateMap.put("universityFillStatus", "1");
			schoolStatusService.updateSchoolStatus(updateMap);
			Map<String, Object> schoolStatusMap = maps.get(0);
			String classId = CommonUtils.getStrValueFromMap(schoolStatusMap,
					"classId", "");
			String collegeId = CommonUtils.getStrValueFromMap(schoolStatusMap,
					"collegeId", "");
			param.put("studentType",
					StudentTypeEnums.ENROLLED_STUDENTS.getCode());
			param.put("studentId", studentId);
			param.put("classId", classId);
			param.put("collegeId", collegeId);
			studentService.updateStudentInfoByMap(param);
			map.put("studentType", String
					.valueOf(StudentTypeEnums.ENROLLED_STUDENTS.getCode()));
			redisUtil.set(token, map);
			logger.info(ServletUtil.getClientIp(request));
		} catch (Exception e) {
			dealException(ErrorEnums.SYSTEM_ERROR, e, apiResult, logger);
		}
		resultMap.put("toUrl", "/auth/successIndex");
		apiResult.setResult(resultMap);
		return apiResult;
	}

	/**
	 * 跳转添加学院页面
	 * 
	 * @param request
	 */
	@RequestMapping(value = "/public/toAddCollege")
	public ModelAndView toAddCollege(HttpServletRequest request) {
		logger.entry(ServletUtil.getClientIp(request), "toAddCollege");
		String toUrl = ServletUtil.getParameterStr(request, "toUrl", "");
		ModelAndView result = new ModelAndView("/h5/addCollege");
		if (!"".equals(toUrl)) {
			result.addObject("toUrl", toUrl);
		}
		logger.info(ServletUtil.getClientIp(request));
		return result;
	}

	/**
	 * 忘记密码
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/public/toBackPassword")
	public ModelAndView toBackPassword(HttpServletRequest request) {
		logger.entry(ServletUtil.getClientIp(request), "toBackPassword");
		ModelAndView result = new ModelAndView("/h5/backPassword");
		logger.info(ServletUtil.getClientIp(request));
		return result;
	}

	/**
	 * 跳转修改密码页面
	 * 
	 * @param request
	 * @author WangYuan
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/auth/modifyPwd")
	public ModelAndView modifyPwd(HttpServletRequest request) {
		logger.entry(ServletUtil.getClientIp(request), "modifyPwd");
		ModelAndView result = new ModelAndView("/h5/xiugaimima");

		String token = sessionUtil.getTokenSession(request);
		Map<String, Object> studentMap = (Map<String, Object>) redisUtil
				.get(token);
		String mood = CommonUtils.getStrValueFromMap(studentMap, "mood", "");
		String studentName = CommonUtils.getStrValueFromMap(studentMap,
				"studentName", "");
		String headPortrait = CommonUtils.getStrValueFromMap(studentMap,
				"headPortrait", "");
		result.addObject("mood", mood);
		result.addObject("studentName", studentName);
		result.addObject("headPortrait", headPortrait);

		return result;
	}


	/**
	 * 招聘跳转修改密码页面
	 *
	 * @param request
	 * @author WangYuan
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/auth/recruitModifyPwd")
	public ModelAndView recruitModifyPwd(HttpServletRequest request) {
		logger.entry(ServletUtil.getClientIp(request), "recruitModifyPwd");
		ModelAndView result = new ModelAndView("/h5/xiugaimimaZP");
		String token = sessionUtil.getTokenSession(request);
		Map<String, Object> studentMap = (Map<String, Object>) redisUtil
				.get(token);
		String studentType = CommonUtils.getStrValueFromMap(studentMap,"studentType","");
		// 如果是业务员跳转到业务员页面
		if (StudentTypeEnums.SALES_MAN.getCode() == Integer
				.valueOf(studentType)) {
			result.addObject("toUrl", "edu/public/salesManLogin");
		}
		return result;
	}

	/**
	 * 修改密码
	 * 
	 * @param request
	 * @author WangYuan
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value = "/auth/doModifyPwd")
	public ApiResult<Map<String, Object>> doModifyPwd(HttpServletRequest request) {
		logger.entry(ServletUtil.getClientIp(request), "doModifyPwd");
		ApiResult<Map<String, Object>> apiResult = new ApiResult<>();
		String oldPassWord = ServletUtil.getParameterStr(request,
				"oldPassWord", "");
		String newPassWord = ServletUtil.getParameterStr(request,
				"newPassWord", "");
		String confirmNewPassWord = ServletUtil.getParameterStr(request,
				"confirmNewPassWord", "");

		try {

			if (StringUtils.isAnyEmpty(oldPassWord, newPassWord,
					confirmNewPassWord)) {
				apiResult.setStatus(ErrorEnums.PASSWORD_EMPTY.getCode());
				apiResult.setMessage(ErrorEnums.PASSWORD_EMPTY.getDesc());
				return apiResult;
			}

			String token = sessionUtil.getTokenSession(request);
			Map<String, Object> map = (Map<String, Object>) redisUtil
					.get(token);
			String mobilePhone = map.get("phoneNumber").toString();
			String studentType = CommonUtils.getStrValueFromMap(map,"studentType","");
			Map<String, Object> studentMap = studentService
					.findMapByPhoneNumberAndStudentType(mobilePhone,studentType);
			if (!Digests.md5(oldPassWord).equals(
					studentMap.get("password").toString())) {
				apiResult.setStatus(ErrorEnums.PASSWORD_AGREE.getCode());
				apiResult.setMessage(ErrorEnums.PASSWORD_AGREE.getDesc());
				return apiResult;
			}

			Map<String, Object> param = new HashMap<>();
			param.put("phoneNumber", mobilePhone);
			param.put("password", Digests.md5(newPassWord));
			studentService.updateStudentInfoByMap(param);
			return apiResult;
		} catch (Exception e) {
			dealException(ErrorEnums.SYSTEM_ERROR, e, apiResult, logger);
			return apiResult;
		}
	}

	/**
	 * 修改密码
	 *
	 * @param request
	 * @author WangYuan
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping(value = "/auth/doModifyPwdByMap")
	public ApiResult<Map<String, Object>> doModifyPwdByZp(HttpServletRequest request) {
		logger.entry(ServletUtil.getClientIp(request), "doModifyPwdByZp");
		ApiResult<Map<String, Object>> apiResult = new ApiResult<>();
		String oldPassWord = ServletUtil.getParameterStr(request,
				"oldPassWord", "");
		String newPassWord = ServletUtil.getParameterStr(request,
				"newPassWord", "");
		String confirmNewPassWord = ServletUtil.getParameterStr(request,
				"confirmNewPassWord", "");

		try {

			if (StringUtils.isAnyEmpty(oldPassWord, newPassWord,
					confirmNewPassWord)) {
				apiResult.setStatus(ErrorEnums.PASSWORD_EMPTY.getCode());
				apiResult.setMessage(ErrorEnums.PASSWORD_EMPTY.getDesc());
				logger.info(apiResult);
				return apiResult;
			}

			String token = sessionUtil.getTokenSession(request);
			Map<String, Object> map = (Map<String, Object>) redisUtil
					.get(token);
			String mobilePhone = map.get("phoneNumber").toString();
			String studentType = CommonUtils.getStrValueFromMap(map,"studentType","");
			Map<String, Object> studentMap = studentService
					.findMapByPhoneNumberAndStudentType(mobilePhone,studentType);
			if (!Digests.md5(oldPassWord).equals(
					studentMap.get("password").toString())) {
				apiResult.setStatus(ErrorEnums.PASSWORD_AGREE.getCode());
				apiResult.setMessage(ErrorEnums.PASSWORD_AGREE.getDesc());
				logger.info(apiResult);
				return apiResult;
			}

			Map<String, Object> param = new HashMap<>();
			param.put("phoneNumber", mobilePhone);
			param.put("password", Digests.md5(newPassWord));
			param.put("studentType", studentType);
			studentService.updatePwdByMap(param);
			logger.info(apiResult);
			return apiResult;
		} catch (Exception e) {
			dealException(ErrorEnums.SYSTEM_ERROR, e, apiResult, logger);
			return apiResult;
		}
	}

	/**
	 * 修改密码
	 * 
	 * @param request
	 * @author WangYuan
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/public/backPassWord")
	public ApiResult<Map<String, Object>> backPassWord(
			HttpServletRequest request) {
		logger.entry(ServletUtil.getClientIp(request), "backPassWord");
		ApiResult<Map<String, Object>> apiResult = new ApiResult<>();

		String newPwd = ServletUtil.getParameterStr(request, "newPwd", "");
		String smsCode = ServletUtil.getParameterStr(request, "smsCode", "");
		String confirmPwd = ServletUtil.getParameterStr(request, "confirmPwd",
				"");
		String mobilePhone = ServletUtil.getParameterStr(request,
				"mobilePhone", "");

		try {

			if (StringUtils
					.isAnyEmpty(newPwd, smsCode, confirmPwd, mobilePhone)) {
				apiResult.setStatus(ErrorEnums.MUST_FIELD_IS_NULL.getCode());
				apiResult.setMessage(ErrorEnums.MUST_FIELD_IS_NULL.getDesc());
				return apiResult;
			}

			Map<String, Object> studentMap = studentService
					.findMapByPhoneNumber(mobilePhone);
			if (null == studentMap) {
				apiResult.setStatus(ErrorEnums.PHONE_NUMBER_NO_EXIST.getCode());
				apiResult
						.setMessage(ErrorEnums.PHONE_NUMBER_NO_EXIST.getDesc());
				return apiResult;
			}

			if (!checkSmsCode(mobilePhone, smsCode,
					SmsTypeEnums.BACK_PASSWORD.getCode())) {
				apiResult.setStatus(ErrorEnums.SMS_CODE_ERROR.getCode());
				apiResult.setMessage(ErrorEnums.SMS_CODE_ERROR.getDesc());
				return apiResult;
			}

			Map<String, Object> param = new HashMap<>();
			param.put("phoneNumber", mobilePhone);
			param.put("password", Digests.md5(newPwd));
			studentService.updateStudentInfoByMap(param);
			return apiResult;
		} catch (Exception e) {
			dealException(ErrorEnums.SYSTEM_ERROR, e, apiResult, logger);
			return apiResult;
		}
	}

	/**
	 * 退出系统
	 * @param request
	 * @author WangYuan
	 * @return
	 */
	@RequestMapping(value = "/auth/loginOut")
	@ResponseBody
	public ApiResult<Map<String, Object>> loginOut(HttpServletRequest request, HttpServletResponse response) {
		logger.entry(ServletUtil.getClientIp(request), "loginOut");
		Map<String, Object> logMap = new HashMap<>();
		ApiResult<Map<String, Object>> apiResult = new ApiResult<>();
		try {
			String token = sessionUtil.getTokenSession(request);
			Object object = redisUtil.get(token);
			if (null != object) {
				redisUtil.delete(token);
				sessionUtil.delete(request, StaticConstants.USER_SESSION_KEY);
//				Cookie[] cookies = request.getCookies();
			}
			logMap.put("mobilePhone", token);
//			Object object1 = redisUtil.get(token);
			logger.info(logMap);
		} catch (Exception e) {
			dealException(ErrorEnums.SYSTEM_ERROR, e, apiResult, logger);
		}
		return apiResult;
	}

	@RequestMapping(value = "/auth/toEditHeadprotrait")
	public ModelAndView toEditHeadprotrait(HttpServletRequest request) {
		logger.entry(ServletUtil.getClientIp(request), "toEditHeadprotrait");
		ModelAndView result = new ModelAndView("/h5/editHeadportrait");
		logger.info(ServletUtil.getClientIp(request));
		return result;
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/auth/toEditStudentInfo")
	public ModelAndView toEditStudentInfo(HttpServletRequest request) {
		logger.entry(ServletUtil.getClientIp(request), "toEditStudentInfo");
		ModelAndView result = new ModelAndView("/h5/editStudentInfo");
		String token = sessionUtil.getTokenSession(request);
		Map<String, Object> map = (Map<String, Object>) redisUtil.get(token);
		String phoneNumber = CommonUtils.getStrValueFromMap(map, "phoneNumber",
				"");
		Map<String, Object> studentMap = studentService
				.findMapByPhoneNumber(phoneNumber);
		String studentName = CommonUtils.getStrValueFromMap(studentMap,
				"studentName", "");
		String headPortrait = CommonUtils.getStrValueFromMap(studentMap,
				"headPortrait", "");
		String wechatNumber = CommonUtils.getStrValueFromMap(studentMap,
				"wechatNumber", "");
		String mood = CommonUtils.getStrValueFromMap(studentMap, "mood", "");
		logger.info(ServletUtil.getClientIp(request));
		result.addObject("studentName", studentName);
		result.addObject("headPortrait", headPortrait);
		result.addObject("wechatNumber", wechatNumber);
		result.addObject("mood", mood);
		result.addObject("phoneNumber", phoneNumber);
		return result;
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/auth/modifyStudentInfo")
	@ResponseBody
	public ApiResult<String> modifyStudentInfo(HttpServletRequest request) {
		logger.entry(ServletUtil.getClientIp(request), "modifyStudentInfo");
		ApiResult<String> apiResult = new ApiResult<>();
		String lujing = ServletUtil.getParameterStr(request, "lujing", "");
		String ming = ServletUtil.getParameterStr(request, "ming", "");
		String dianhua = ServletUtil.getParameterStr(request, "dianhua", "");
		String weixin = ServletUtil.getParameterStr(request, "weixin", "");
		String xinqing = ServletUtil.getParameterStr(request, "xinqing", "");

		String token = sessionUtil.getTokenSession(request);
		Map<String, Object> map = (Map<String, Object>) redisUtil.get(token);
		try {
			String studentId = CommonUtils.getStrValueFromMap(map, "studentId",
					"");
			Map<String, Object> updateMap = new HashMap<>();
			updateMap.put("lujing", lujing);
			updateMap.put("studentId", studentId);
			updateMap.put("studentName", ming);
			updateMap.put("updatePhoneNumber", dianhua);
			updateMap.put("wechatNumber", weixin);
			updateMap.put("mood", xinqing);
			studentService.updateStudentInfoByMap(updateMap);
			Map<String, Object> findMap = new HashMap<>();
			findMap.put("studentId", studentId);
			Map<String, Object> stuMap = studentService
					.findStudentMapOneByMap(findMap);
			redisUtil.set(token, stuMap);
		} catch (Exception e) {
			dealException(ErrorEnums.SYSTEM_ERROR, e, apiResult, logger);
		}
		return apiResult;
	}

}
